package cn.net.csit.platform_cloud.basicmodel.service.impl;

import cn.net.csit.platform_cloud.basicmodel.domain.BasicPropertyDictionaryDomain;
import cn.net.csit.platform_cloud.basicmodel.domain.BasicPropertyDictionaryDomainExample;
import cn.net.csit.platform_cloud.basicmodel.domain.BasicPropertyGroupDomain;
import cn.net.csit.platform_cloud.basicmodel.domain.BasicPropertyGroupRelationDomain;
import cn.net.csit.platform_cloud.basicmodel.mapper.BasicPropertyDictionaryDomainMapper;
import cn.net.csit.platform_cloud.basicmodel.service.*;
import cn.net.csit.platform_cloud.utils.MapAndStringUtil;
import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class BasicPropertyDictionaryServiceImpl implements IBasicPropertyDictionaryService {

    @Autowired
    private BasicPropertyDictionaryDomainMapper mapper;
    @Autowired
    private IBasicPropertyGroupService iBasicPropertyGroupService;
    @Autowired
    IBasicObjectPropertyRelationService basicObjectPropertyRelationService;
    @Autowired
    IBasicPropertyGroupRelationService iBasicPropertyGroupRelationService;
    @Autowired
    IBackupDataService backupDataService;
    @Override
    public int insert(BasicPropertyDictionaryDomain recode) {
        //添加属性组字段转换存储
        BasicPropertyDictionaryDomain domain= reversePropGroup(recode);
        return mapper.insert(domain);
    }

    @Override
    public BasicPropertyDictionaryDomain selectById(String uuid) {
        return mapper.selectByPrimaryKey(uuid);
    }

    @Override
    public int updateByPrimaryKey(BasicPropertyDictionaryDomain recode)
    {   //添加属性组字段转换存储
        BasicPropertyDictionaryDomain domain= reversePropGroup(recode);
        //添加新增关系代码
        return mapper.updateByPrimaryKey(domain);
    }

    private BasicPropertyDictionaryDomain reversePropGroup(BasicPropertyDictionaryDomain recode) {
        //判断
        if(null==recode.getPropGroupName()||recode.getPropGroupName().equals("")){
            //增加默认分组
            recode.setPropGroupName("未命名分组");
         }else{
            List propGrouplist = (List)JSONUtils.parse(recode.getPropGroupName());
            recode.setPropGroupName(propGrouplist.toString().substring(1,propGrouplist.toString().lastIndexOf(']')));
            Map<String,String> map=new HashMap<>();
            propGrouplist.forEach((item)->{
                map.put("propGroupName",item.toString());
                List<BasicPropertyGroupDomain> list=iBasicPropertyGroupService.getAll(map);
                //
                if(null==list||list.size()==0){
                    //新增属性组记录
                    BasicPropertyGroupDomain domainGroup=new BasicPropertyGroupDomain();
                    domainGroup.setPropGroupName(item.toString());
                    iBasicPropertyGroupService.insert(domainGroup);
                }
            });
        }

        return recode;
    }

    @Override
    public int deleteByPrimaryKey(String uuid) {

        //删除对象属性关系表
        basicObjectPropertyRelationService.deleteByPropUuid(uuid);
        //添加--删除属性组关系表代码
        Map<String,String> map=new HashMap<>();
        map.put("prop_uuid",uuid);
        iBasicPropertyGroupRelationService.deleteRelation(map);
        return mapper.deleteByPrimaryKey(uuid);
    }

    @Override
    public List<BasicPropertyDictionaryDomain> getAll() {
        BasicPropertyDictionaryDomainExample example=new BasicPropertyDictionaryDomainExample();
        BasicPropertyDictionaryDomainExample.Criteria criteria= example.createCriteria();
        criteria.andPropCodeIsNotNull();
        return mapper.selectByExample(example);
    }

    @Override
    public List<BasicPropertyDictionaryDomain> getAllBySql(Map<String,String> map) {
        BasicPropertyDictionaryDomainExample example=new BasicPropertyDictionaryDomainExample();
        BasicPropertyDictionaryDomainExample.Criteria criteria= example.createCriteria();
        if(null!=map.get("propGroupName")&&!map.get("propGroupName").equals("")){
            criteria.andPropGroupNameLike("%"+map.get("propGroupName")+"%");
        }
        if(null!=map.get("propName")){
            criteria.andPropNameLike("%"+map.get("propName")+"%");
        }

        return mapper.selectByExample(example);

    }

    //先查分组，再查属性
    @Override
    public List<Map<String, Object>> getAllByGroup(Map<String, String> params) {
        List<Map<String,Object>> result=new ArrayList<>();//属性组集合
        List<BasicPropertyGroupDomain> domainGroupList=new ArrayList<>();
        if(null!=params.get("propGroupName")){
            domainGroupList=iBasicPropertyGroupService.getAll(params);
        }else{
            domainGroupList=iBasicPropertyGroupService.getAll();//所有分组
        }


        if(null!=domainGroupList&&domainGroupList.size()>0){
            //所有遍历集合，将查到的数据，分组
            for(BasicPropertyGroupDomain domainGroup:domainGroupList){
                //根据属性组名称查询
                Map<String,String > groupName=new HashMap();
                groupName.put("propGroupName",domainGroup.getPropGroupName());
                if(null!=params.get("propName")){
                    groupName.put("propName",params.get("propName"));
                }
                //模糊查询
               // List<Map<String,String>> domainPropList=getAllBySql(groupName);

                List<BasicPropertyDictionaryDomain> domainPropList=getAllBySql(groupName);

                if(null!=result&&result.size()>0){
                    boolean flag=false;
                    for (Map<String,Object> mm:result){

                        if(mm.get("propGroupName").equals(domainGroup.getPropGroupName())){
                                flag=true;
                                break;
                        }else{
                                continue;
                        }
                    }
                    if(flag){
                        continue;
                    }else{
                        //新建集合添加
                        Map<String,Object> map=new HashMap<>();
                        map.put("propGroupName",domainGroup.getPropGroupName());
                        map.put("children",getDomainPropList(domainPropList,domainGroup.getPropGroupName()));
                        result.add(map);
                    }
                }else{
                    //新建集合添加
                    Map<String,Object> map=new HashMap<>();
                    map.put("propGroupName",domainGroup.getPropGroupName());
                    map.put("children",getDomainPropList(domainPropList,domainGroup.getPropGroupName()));
                    result.add(map);
                }
            }
        }
        return result;
    }

    public List<BasicPropertyDictionaryDomain> getDomainPropList(List<BasicPropertyDictionaryDomain> domainPropList,String propGroupName) {
        domainPropList.forEach(item -> {
            item.setPropGroupName(propGroupName);
        });
        return domainPropList;
    }

    @Override
    public List<BasicPropertyDictionaryDomain> getAll(Map<String, String> map) {

        BasicPropertyDictionaryDomainExample example=new BasicPropertyDictionaryDomainExample();
        BasicPropertyDictionaryDomainExample.Criteria criteria= example.createCriteria();
        criteria.andPropCodeIsNotNull();
        if(null!=map.get("propGroupName")){
            criteria.andPropGroupNameLike(map.get("propGroupName"));
        }
        if(null!=map.get("propName")){
            criteria.andPropNameLike(map.get("propName"));
        }

        return mapper.selectByExample(example);
    }
    //增加属性组名称
    @Override
    public int updateByPrimaryKey(String uuid,String params) {
        int res=0;
        BasicPropertyDictionaryDomain record= mapper.selectByPrimaryKey(uuid);
        if(null!=record.getPropGroupName()&&record.getPropGroupName().length()>0){
            String s=record.getPropGroupName();
            if(null!=params&&!s.contains(params)){
                    s=s+","+params;
                    record.setPropGroupName(s);
                    res=mapper.updateByPrimaryKey(record);
            }
        }
        if(null==record.getPropGroupName()||record.getPropGroupName().length()==0){
            record.setPropGroupName(params);
            res=mapper.updateByPrimaryKey(record);
        }
        return res;
    }
    @Override
    public int deleteByPropGroupName(String propGroupName) {
        Map<String,String> map = new HashMap<>();
        map.put("prop_group_name",propGroupName);
        try {
            iBasicPropertyGroupService.deleteByPrimaryKey(iBasicPropertyGroupService.getAllByGN(map).get("uuid"));
            //更新属性表属性组字段
            List<BasicPropertyDictionaryDomain> propList =  getAllBySql(map);
            propList.forEach(item -> {
                List groupName = Arrays.asList("[" + item.getPropGroupName() + "]");
                groupName.remove(propGroupName);
                item.setPropGroupName(groupName.toString().substring(1,groupName.toString().lastIndexOf("]")));
                updateByPrimaryKey(item);
            });

            //添加--删除属性组关系表代码
            Map<String,String> params=new HashMap<>();
            params.put("prop_uuid",iBasicPropertyGroupService.getAllByGN(map).get("uuid"));
            iBasicPropertyGroupRelationService.deleteRelation(params);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    //减少属性组名称
    @Override
    public int updateRedurceByPrimaryKey(String uuids, String params) {

        return 0;
    }


    //修改属性组名称
    @Override
    public int updateByGroupNameList(String oldGroupName, String newGroupName) {
        int res=0;
        //根据旧属性组名称，查询属性集合
        Map<String, String> map=new HashMap<>();
        map.put("propGroupName",oldGroupName);
        List<BasicPropertyDictionaryDomain> list= getAll(map);
        //遍历属性集合，根据将新属性组名称覆盖旧属性名称
        for(BasicPropertyDictionaryDomain domain:list){
            if(domain.getPropGroupName().contains(",")){
                domain.setPropGroupName(newGroupName);
            }

            //将属性集合保存
            res=mapper.updateByPrimaryKey(domain);
        }
        return res;
    }

    @Override
    public Map<String, String> getPropNameByPropCode(Map<String, Object> map) {
        Map<String, String> res=new HashMap<>();
        if(null!=map&&map.size()>0){
            for(Map.Entry<String, Object> vo : map.entrySet()){
                if(vo.getKey().equals("attrInfor")){
                    List<Map<String,String>> objList=new ArrayList<>();
                    List<Map<String,String>> propList=new ArrayList<>();
                    List<Map<String,String>> list=new ArrayList<>();
                    Map<String, String> mmap= MapAndStringUtil.stringToMap(vo.getValue().toString()) ;
                    if(null != mmap &&null!= mmap.get("type_code")){
                        //1.根据type_code查询对象表uuid集合A
                        StringBuilder sb = new StringBuilder();
                        sb.append(" SELECT uuid as obj_uuid FROM basic_obj_dictionary ");
                        sb.append(" where organ_type='"+ mmap.get("type_code")+"'");
                        objList= backupDataService.customQueryItem(sb);

                    }
                    if(null != mmap&&null!=mmap.get("prop_code")){
                        //2.根据prop_code查询属性表uuid,prop_name集合B
                        StringBuilder sb = new StringBuilder();
                        sb.append(" SELECT uuid as prop_uuid,prop_name,prop_type FROM basic_property_dictionary ");
                        sb.append(" where prop_code='"+mmap.get("prop_code")+"'");
                        propList= backupDataService.customQueryItem(sb);
                    }
                    //3.遍历集合A，遍历集合B，根据对象uuid,属性uuid,查询关系表是否存在
                    if(null!=objList&&objList.size()>0){
                        if(null!=propList&&propList.size()>0){
                            for(Map<String, String> obj:objList){
                                for(Map<String, String> prop:propList){
                                    Map<String, String> params=new HashMap<>();
                                    params.put("obj_uuid",obj.get("obj_uuid"));
                                    params.put("prop_uuid", prop.get("prop_uuid"));

                                    StringBuilder selectSql=new StringBuilder();
                                    selectSql.append("select * from basic_obj_property_relation where prop_uuid = '"+ params.get("prop_uuid") +"'"+" and obj_uuid='"+params.get("obj_uuid")+"'") ;
                                    //查询关系
                                     list= backupDataService.customQueryItem(selectSql);
                                     //
                                    //4.如果存在则将集合B的prop_name数据返回
                                    if(null!=list&&list.size()>0){
                                        if(null!=prop&&null!=prop.get("prop_name")&&!prop.get("prop_name").equals("")){
                                            res.put("prop_name",prop.get("prop_name"));

                                        }else{
                                            res.put("prop_name","");
                                        }
                                        if(null!=prop&&null!=prop.get("prop_type")&&!prop.get("prop_type").equals("")){
                                            res.put("prop_type",prop.get("prop_type"));

                                        }else{
                                            res.put("prop_type","");
                                        }
                                    }
                                }
                            }
                        }
                    }

                }

            }


        }


        return res;
    }

    @Override
    public void updatePropGroupRelation(BasicPropertyDictionaryDomain recode) {
        //根据属性编码,查询属性组名称
        StringBuilder selectSql=new StringBuilder();
        selectSql.append("select uuid as prop_uuid,prop_group_name from basic_property_dictionary where prop_code = '"+ recode.getPropCode() +"'") ;
        //查询关系
        List<Map<String,String>> list= backupDataService.customQueryItem(selectSql);
        List<Map<String,String>> groups=new ArrayList<>();
        if(null!=list&&list.size()>0&&null!=list.get(0)){
            if(null!=list.get(0).get("prop_group_name")&&!list.get(0).get("prop_group_name").equals("")){
                //根据属性组名称查询属性组uuid
                if(list.get(0).get("prop_group_name").contains(",")){
                    String[] s=list.get(0).get("prop_group_name").split(",");
                    for(String temp:s){
                        StringBuilder selectGroupSql=new StringBuilder();
                        selectSql.append("select uuid as prop_group_uuid,prop_group_name from basic_property_group where prop_group_name = '"+ temp+"'") ;
                        List<Map<String,String>> listGroup= backupDataService.customQueryItem(selectGroupSql);
                        if(null!=listGroup&&listGroup.size()>0){
                            for(Map<String,String> mm:listGroup){
                                Map<String,String> group=new HashMap<>();
                                group.put("prop_group_uuid",mm.get("prop_group_uuid"));
                                groups.add(group);
                            }
                        }
                    }
                }else{
                    StringBuilder selectGroupSql=new StringBuilder();
                    selectGroupSql.append("select uuid as prop_group_uuid,prop_group_name from basic_property_group where prop_group_name = '"+ list.get(0).get("prop_group_name")+"'") ;
                    List<Map<String,String>> listGroup= backupDataService.customQueryItem(selectGroupSql);
                    if(null!=listGroup&&listGroup.size()>0){
                        if(null!=listGroup.get(0)&&null!=listGroup.get(0).get("prop_group_uuid")&&!listGroup.get(0).get("prop_group_uuid").equals("")){
                            Map<String,String> group=new HashMap<>();
                            group.put("prop_group_uuid",listGroup.get(0).get("prop_group_uuid"));
                            groups.add(group);
                        }
                    }
                }


            }
            //

            // 根据属性uuid，属性组uuid，查询关系，判断是否要新增关系
            for(Map<String,String> gg:groups){
                Map<String,String> params=new HashMap<>();
                params.put("prop_group_uuid",gg.get("prop_group_uuid"));
                params.put("prop_uuid",list.get(0).get("prop_uuid"));
                List<Map<String,String>> listRelation=iBasicPropertyGroupRelationService.selectRelation(params);
                if(null==listRelation||listRelation.size()<=0){
                    BasicPropertyGroupRelationDomain recordDomain=new BasicPropertyGroupRelationDomain();
                    recordDomain.setPropGroupUuid(params.get("prop_group_uuid"));
                    recordDomain.setPropUuid(params.get("prop_uuid"));
                    iBasicPropertyGroupRelationService.insert(recordDomain);
                }
            }
        }


    }


}
